package sensimulator.intersection;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.JPanel;

import sensimulator.intersection.lanes.Lane;
import sensimulator.intersection.traffic.TrafficUser;

public class Painter extends JPanel {

	public static final int BACKGROUND_LAYER = 0;
	
	public static final int OBJECTS_LAYER = 1;
	
	public static final int TRAFFIC_LAYER = 2;
	
	public static final int TOP_LAYER = 3;
	
	public static final String BACKGROUND_FILE = "resources/kruispunt.png"; 
	
	private Intersection intersection;
	
	private Image backgroundImage;
	
	private Vector<Drawable> drawables;

	public Painter(Intersection intersection) {
		super();
		
		this.intersection = intersection;
		drawables = new Vector<Drawable>();
		
		backgroundImage = Toolkit.getDefaultToolkit().createImage(BACKGROUND_FILE);
		setBounds(0, 0, backgroundImage.getWidth(this), backgroundImage.getHeight(this));
		setLayout(null);
	}
	
	public void addDrawable(Drawable d) {
		synchronized (drawables) { 
			drawables.add(d);
			Collections.sort(drawables, new Comparator<Drawable>() {

				@Override
				public int compare(Drawable a, Drawable b) {
					return a.getZOrder() - b.getZOrder();
				}
				
			});
		} 
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		
		g.drawImage(backgroundImage, 0, 0, this);
		
		synchronized (drawables) { 
			for (Iterator<Drawable> i = drawables.iterator(); i.hasNext(); ) {
				Drawable d = i.next();
				if (d.isDisposed())
					i.remove();
				else
					d.paint(g, this);
			}
		}
		
		/*
		for (Lane lane : intersection.getLanes()) {
			synchronized (lane.getTraffic()) {
				for (TrafficUser user : lane.getTraffic())
					user.paint(g, this);
				
			}
			
			lane.paint(g, this);
		}
		*/
	}
	
}
